package com.sq.partner.manager.controller;

import com.sq.partner.manager.common.Config;
import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.dao.impl.BaseDaoImpl;
import com.sq.partner.manager.mybatis.model.CarPushDataQuery;
import com.sq.partner.manager.mybatis.model.CoreDept;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewaySubChannel;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.TradAgentInfo;
import com.sq.partner.manager.mybatis.model.TradAgentInfoRela;
import com.sq.partner.manager.mybatis.model.TradSaleAgent;
import com.sq.partner.manager.service.CarPushDataQueryService;
import com.sq.partner.manager.service.IGatewayAgentInfoMtService;
import com.sq.partner.manager.service.IGatewaySubChannelService;
import com.sq.partner.manager.service.JSCDService;
import com.sq.partner.manager.util.*;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/carDataManagement")
public class CarDataManageController {
    private static Logger logger = LogUtil.getLog(CarDataManageController.class);
	@Resource
	private CarPushDataQueryService carPushDataQueryService;
	@Resource
	private IGatewayAgentInfoMtService agentInfoMtService;
	@Resource
	private IGatewaySubChannelService gatewaySubChannelService;
	@Resource
	private JSCDService jscdService;
	/**
	 * 跳转推送数据查询页面
	 */
	@RequestMapping(value = "/pushDateQuery")
	public String page(HttpSession session,ModelMap model) throws Exception {
		return "carDataManagement/pushDateQueryPage";
	}
	/***
	 * 推送数据查询
	 * @param session
	 * @param model
	 * @param carVin
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/carPushDateQuery")
	@ResponseBody
	public Page<CarPushDataQuery> dataQuery(HttpSession session,ModelMap model,String carVin) throws Exception { 
		Page<CarPushDataQuery> page = new Page<CarPushDataQuery>();
		try{
			List<CarPushDataQuery> pushDataList = carPushDataQueryService.pushDataQuery(carVin);
			if(null != pushDataList && pushDataList.size()>0){
				page.setData(pushDataList);
			}else{
				page.setMessage("该车架号暂无推送数据！");
			}
		}catch(Exception e){
            logger.info(e);
            page.setResult("error");
            page.setMessage("查询数据失败 请联系管理员！");
            return page;
		}
		return page;
	}
	/**
	 * 销售渠道信息页面
	 */
	@RequestMapping(value = "/salesChannelInfoPage")
	public String salesChannelInfoPage(HttpSession session,ModelMap model) throws Exception {
		//新业务来源
		List<DictDto> newBSList = DictCache.getDict(Constants.DICT_NEW_BUSINESS_SOURCE);
		//20230509增加处理，部分业务来源停用
		List<DictDto> newBSListIndex = new ArrayList<DictDto>();
		for(DictDto dict : newBSList){
			if(dict.getOtherName().equals("0")){
				dict.setCodeName(dict.getCodeName() + "(已停用)");
				newBSListIndex.add(dict);
			}else {
				newBSListIndex.add(dict);
			}
		}
		newBSList = newBSListIndex;
		//旧业务来源
		List<DictDto> oldBSList = DictCache.getDict(Constants.CAR_DICT_OLD_BUSINESS_SOURCE);
		//归属渠道
		List<DictDto> btcList = DictCache.getDict(Constants.DICT_BELONG_TO_CHANNEL);
		//渠道类型
		List<DictDto> channelList = DictCache.getDict(Constants.DICT_CHANNEL_TYPE);
		//合作伙伴
		List<DictDto> partners = DictCache.getDict(Constants.CAR_PARTNER);
		model.put("newBSList", newBSList);
		model.put("oldBSList", oldBSList);
		model.put("btcList", btcList);
		model.put("channelList", channelList);
		model.put("partners", partners);
		return "carDataManagement/salesChannelInfoPage";
	}
	/***
	 * 车险代理信息条件查询
	 */
	@RequestMapping( value="/carAgentInfoPageQuery")
	@ResponseBody
	public Page<TradAgentInfo> carAgentInfoSelect(HttpSession session,Page<TradAgentInfo> page,String channelCode,String dptCde,String subChannelCode,String subChannelName)throws Exception{
		 Map<String, Object> paramMap = SqlUtil.buildPageMap(page);
		 GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		  if(StrUtil.isNotEmpty(user.getDepartmentStr()) && !"'00'".equals(user.getDepartmentStr())){
			  paramMap.put("dptCde", user.getDepartmentStr());
		  }
		  if(StrUtil.isNotEmpty(channelCode)){
			  paramMap.put("channelCode", channelCode);
		  }
		  if(StrUtil.isNotEmpty(dptCde)){
			  paramMap.put("dptCode", dptCde+"%");
		  }else{
			  paramMap.put("dptCodeLike", "Y");
		  }
		  if(StrUtil.isNotEmpty(subChannelCode)){
			  paramMap.put("subChannelCode", subChannelCode+"%");
		  }
		  if(StrUtil.isNotEmpty(subChannelName)){
			  paramMap.put("subChannelName", subChannelName+"%");
		  }
		  page.setMap(paramMap);
		  Page<TradAgentInfo> carAgentPage = carPushDataQueryService.queryCarAgentPage(page);
		  return carAgentPage;
	}
	/**
	 * 销售渠道信息模板下载
	 */
	@RequestMapping(value = "/templateDownload")
	public void templateDownload(HttpServletResponse response,HttpServletRequest request) throws IOException{
		String classPath=this.getClass().getResource("").getPath();
		String path="";
			path = (classPath.substring(0,classPath.indexOf("/WEB-INF/")+8)+ "/file/CarSalesChannelTemplate.xls").replace("/WEB-INF", "");
		// 以流的形式下载文件
		InputStream inputStream=null;
		OutputStream outputStream =null;
		try {
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			inputStream = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[inputStream.available()];
			inputStream.read(buffer);
			response.reset();
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
			response.addHeader("Content-Length", "" + file.length());
			outputStream = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			outputStream.write(buffer);
			outputStream.flush();
		}catch (Exception e) {
			logger.info(e);
		}finally{
			if(null!=inputStream){
				inputStream.close();
			}
			if(null!=outputStream){
				outputStream.close();
			}
		}
	}
	/**
	 * 加载机构列表，需要传入页面选择的“投保单位代码”进行查询
	 */
	@RequestMapping(value = "/loadCoreDept")
	public @ResponseBody Page<CoreDept> queryAllCoreDepts(HttpSession session ,Page<CoreDept> page,String deptCode,String deptName) throws Exception{
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		Map<String, Object>map=new HashMap<String, Object>();
		/**条件判断*/
		if(StrUtil.isNotEmpty(deptCode)){
			map.put("deptCode", deptCode+"%");
		}
		if(StrUtil.isNotEmpty(deptName)){
			map.put("deptName","%"+deptName+"%");
		}
		page.setMap(map);
		if(null != gatewayuser && StrUtil.isNotEmpty(gatewayuser.getDepartmentStr())){
			logger.info("登录用户"+gatewayuser.getUserCode()+"用户机构"+gatewayuser.getDepartmentStr());
			 page = carPushDataQueryService.queryCoreDeptForCar(page, gatewayuser.getDepartmentStr());
			
		}
		return page;
	}
	// 归属渠道-渠道类型-新业务来源处理
	@RequestMapping(value = "/loadSubDropList")
	public @ResponseBody List<DictDto> getSubDropListData(String codeType, String parentCode) throws Exception {
		List<DictDto> list = new ArrayList<DictDto>();
		if (StrUtil.isNotEmpty(codeType) && StrUtil.isNotEmpty(parentCode)) {
			List<DictDto> subDataList = DictCache.getDictDataByParentCode(codeType, parentCode);
			//复制list
			list.addAll(subDataList);
			//倒序
			Collections.reverse(list);
			DictDto dd = new DictDto();
			dd.setCode("");
			dd.setCodeName("----请选择----");
			list.add(dd);
			//倒序
			Collections.reverse(list);
			return list;
		}else{
			DictDto dd = new DictDto();
			dd.setCode("");
			if("channel_type".equals(codeType)){
				dd.setCodeName("----请选择归属渠道----");
			}else if("new_business_source".equals(codeType)){
				dd.setCodeName("----请选择渠道类型----");
			}
			list.add(dd);
		}
		return list;
	}
	//选取旧业务来源
	@RequestMapping(value = "/chooseBsnsType")
	public @ResponseBody DictDto chooseBsnsType(String parentCode,String newBsnsCode) throws Exception {
		DictDto dd = new DictDto();
		if (StrUtil.isNotEmpty(parentCode)&&StrUtil.isNotEmpty(newBsnsCode)) {
			List<DictDto> subDataList = DictCache.getDictDataByParentCode("new_business_source", parentCode);
			for (DictDto dictDto : subDataList) {
				if(newBsnsCode.equals(dictDto.getCode())){
					return dictDto;
				}
			}
		}else{
			dd.setOtherCode("");
		}
		return dd;
	}
	@RequestMapping(value = "/saveAgentMtInfo")
	@ResponseBody
	public Result saveAgentMtInfo(HttpSession session,String flag,TradAgentInfo agentInfo,String jqMax,String jqMin,String syMax,String syMin) throws Exception {
		if("update".equals(flag) && (null == agentInfo.getId())){
			return Result.error("操作失败，代理信息唯一标识不允许为空");
		}
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		if(StrUtil.isNotEmpty(agentInfo.getAgentNo())){
			RedisUtil redis = RedisUtil.getInstance();
			Map<String, String> agentMap = redis.getValue(agentInfo.getAgentNo());
			if(null == agentMap || "0".equals(agentMap.get("validStatus"))){
				return Result.error("代理人编码在销管系统不存在或已失效！请检查！");
			}
		}
		return carPushDataQueryService.saveAgentMtInfo(flag,user,agentInfo,jqMax,jqMin,syMax,syMin);
	}
	@RequestMapping("/batchImportAgencyInfoForCar")
	public void batchImportAgencyInfoForCar(@RequestParam(value="excelFile",required=false) MultipartFile excelFile,HttpServletResponse response,HttpSession session,String agentType)throws Exception{
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		PrintWriter out = null;
		InputStream input = null;
		Page<String>  page = new Page<String>();
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		try {
			out = response.getWriter();
			input = excelFile.getInputStream();
			carPushDataQueryService.batchImportAgents(input,session,gatewayuser);
			logger.info("EXCEL导入成功");
			page.setResult("success");
			page.setMessage((String)session.getAttribute("result"));
		} catch (Exception e) {
			logger.info("---------Excel导入失败",e);
			page.setResult("error");
			page.setMessage(e.getMessage());
		} finally {
			if(null!=input){
				try{
					input.close();
				}catch(Exception e){
					logger.warn("关闭流失败！", e);
				}
			}
			out.write(JsonUtils.toJson(page));
			try {
				out.close();
			} catch (Exception e) {
				logger.warn("关闭流失败！", e);
			}
		}
	}
	/***
	 * 意健险销售渠道配置信息查询
	 * @param agentId
	 * @param subchannelCode
	 * @param deptCode
	 * @return
	 * @throws SQLException 
	 * @throws AppException 
	 */
	@RequestMapping(value ="/nlifeTradAgentInfoQuery")
	@ResponseBody
	public Map<String,Object> nlifeTradAgentInfoQuery(String agentId,String channelCode,String subchannelCode,String key,String deptCode,String productType) throws Exception {
		Map<String, Object> paramMap = new HashMap<String,Object>();
		if("INSAIC".equals(channelCode)){
			String agentInfo = "";
			String serviceInfo = "";
			String circuitFlag = "N";
			String agentInfoName = "";
			List<DictDto> insaicNlifeSwitchList = DictCache.getDict(Constants.INSAIC_NLIFE_SWITCH);
				if(StrUtil.isNotEmpty(insaicNlifeSwitchList.get(0).getCode())&&insaicNlifeSwitchList.get(0).getCode().contains(deptCode.substring(0, 2))){
					List<DictDto> dictInfo = getDictInfo("insaic_cfiAgents%",subchannelCode,"YM");
					if(null!=dictInfo && dictInfo.size()>0){
						agentInfo = dictInfo.get(0).getCode();
						if(dictInfo.get(0).getOtherName() != null ){
							agentInfoName = dictInfo.get(0).getOtherName();
						}
					}
					circuitFlag = "Y";
				}else{
					List<DictDto> dictInfo = getDictInfo("insaic_cfiAgents%",deptCode.substring(0, 2)+"%","N");
					Map<String, String> deptMap = new HashMap<String, String>();
					if(null!=dictInfo && dictInfo.size()>0){
						for (DictDto dictDto : dictInfo) {
							deptMap.put(dictDto.getOtherCode(),dictDto.getCode());
						}
						for (int i=deptCode.length();i>=2;i--) {
							if(StrUtil.isNotEmpty(deptMap.get(deptCode.substring(0, i)))){
								agentInfo = deptMap.get(deptCode.substring(0, i));
								break;
							}
						}
					}
				}
				List<DictDto> servicesDictInfo = getDictInfo("INSAIC_NLIFE_SERVICE%",subchannelCode,"Y");
				if(null!=servicesDictInfo && servicesDictInfo.size()>0){
					serviceInfo = servicesDictInfo.get(0).getCode();
				}
				paramMap.put("external_agentInfo", agentInfo);
				paramMap.put("external_serviceInfo", serviceInfo);
				paramMap.put("circuit_flag", circuitFlag);
				paramMap.put("agentInfoName", agentInfoName);
				
		}
		if(StrUtil.isNotEmpty(key)){
			TradAgentInfo agentInfo = new TradAgentInfo();
			agentInfo.setChannelCode(channelCode);
			agentInfo.setSubChannelCode(key);
			agentInfo.setProductType(productType);
			List<TradAgentInfo> tradAgentInfoList = carPushDataQueryService.queryTradAgentInfo(agentInfo);
			if(null!=tradAgentInfoList && tradAgentInfoList.size()>0){
				paramMap.put("internal_tradinfo",tradAgentInfoList.get(0));
			}
		}
		return paramMap;
	}
	@RequestMapping(value ="/savaorupdateInternalTradInfo")
	@ResponseBody
	public Map<String,Object> savaorupdateInternalTradInfo(HttpSession session,TradAgentInfo agentInfo,String carAgentid,String internalNlifeid,String carSubChannelCode)throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		//销管校验
		Map<String,Object> reqxmlMap = new HashMap<String, Object>();
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String code = sf.format(new Date());
		reqxmlMap.put("SERIALNUMBER",code);
		reqxmlMap.put("tradAgentInfo",agentInfo);
		List<DictDto> newBusinessSource = DictCache.getDict("new_business_source");
		String agentType = getAgentTypeByNewBsnsType(agentInfo.getNewBsnsType(),newBusinessSource);
		reqxmlMap.put("AGENTTYPE",agentType);
		reqxmlMap.put("channleType",agentInfo.getChannleType().substring(0,1));
		String xml = "";
		String responseXml = ""; //交易系统返回结果报文
		xml = FreeMarkerUtil.process("/app/saleESB/30005.ftl",reqxmlMap); //转化后的报文
		logger.info("查询交易系统的报文:"+xml);
		responseXml = HttpConnectorUtil.interaction(Config.getProp("salemanage.check.url"),xml,agentInfo.getChannelCode(), Constants.GW_CH_TX_30005);
		logger.info("交易系统返回报文"+responseXml);
		Document document = DocumentHelper.parseText(responseXml);
		Element root = document.getRootElement();
		String resultCode = jscdService.selectSingleNodeByRoot(root , "/XML/HEAD/RESMSGCODE") == null ? "" : jscdService.selectSingleNodeByRoot(root, "/XML/HEAD/RESMSGCODE") ;  //返回码
		if("".equals(resultCode) || resultCode.length() != 4 || (!"0000".equals(resultCode) && !"0001".equals(resultCode))){
			//预期之外的返回值
			resultCode = "9999";
		}
		map.put("resultCode",resultCode);
		if("0001".equals(resultCode)){
			//校验有错
			List<Element> body = root.selectNodes("/XML/BODY");
			String result = "";
			for (Element element : body) {
				Iterator<Element> iterator = element.elementIterator();
				while (iterator.hasNext()){
					String errorMsg = iterator.next().getText();
					if (!"1".equals(errorMsg) && !"0".equals(errorMsg)){
						result = result + errorMsg + "<br>";
					}
				}
			}
			map.put("result",result);
			return map;
		}else if("9999".equals(resultCode)){
			String errorInfo = root.selectSingleNode("/INSUREQRET/HEAD/RESULTCODE") == null ? "系统错误 请联系管理员" : root.selectSingleNode("/INSUREQRET/HEAD/RESULTCODE").getText();
			throw new AppException(errorInfo);
		}
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		agentInfo.setOperUser(user.getUserid());
		agentInfo.setOperTime(new Date());
		boolean flag = carPushDataQueryService.internalTradInfoaddorupdate(agentInfo, internalNlifeid, carAgentid, carSubChannelCode);

		if(flag){
			map.put("success", agentInfo);
		}else{
			map.put("error", "添加失败请联系管理员");
		}
		return map;
	}
	
	/**
	 * 查询删除的车险网点是否有关联的意健险网点配置信息
	 * @param id 车险网点代理信息id
	 * @param flag  deleteAll：车险配置有关联意外险配置，一并删除<br>
	 *              deleteCY:只删除意外险配置<br>
	 *              delete：车险配置无关联意外险配置，删除车险配置
	 * @return
	 */
	@RequestMapping(value = "/deleteSaleInfo")
	@ResponseBody
	public Result deleteSaleInfo(String id, String flag,String channelCode, String subChannel) throws Exception {
		// 当前需要删除的销售配置信息id
		TradAgentInfo agentInfo = new TradAgentInfo();
		agentInfo.setId(Long.parseLong(id.trim()));
		// 当前配置信息的关联方案信息
		TradAgentInfoRela tradAgentInfoRela = new TradAgentInfoRela();
		tradAgentInfoRela.setAgentInfoId(Long.parseLong(id.trim()));
		// 当前需要删除的销售配置
		List<TradAgentInfo> tradAgentInfoList = carPushDataQueryService.queryTradAgentInfo(agentInfo);
		TradAgentInfo tradAgentInfo = tradAgentInfoList.get(0);
		if (tradAgentInfo != null) {
			if ("deleteAll".equals(flag)) {
				// 查询当前车险销售渠道配置关联的意健险销售渠道配置
				TradAgentInfo agentInfoCY = new TradAgentInfo();
				agentInfoCY.setSubChannelCode(tradAgentInfo.getKey1());
				agentInfoCY.setChannelCode(tradAgentInfo.getChannelCode());
				List<TradAgentInfo> tradAgentInfoList2 = carPushDataQueryService.queryTradAgentInfo(agentInfoCY);
				// 获取意健险销售渠道配置
				TradAgentInfo tradAgentInfoCY = tradAgentInfoList2.get(0);
				// 查关联方案
				List<TradAgentInfoRela> tradAgentInfoRelaList = carPushDataQueryService.queryCarAgentRelaInfo(tradAgentInfoRela);
				if (tradAgentInfoRelaList.size() > 0) {
					// 如果有关联方案，删除掉
					 agentInfoMtService.deleteTradAgentInfoRela(id.trim());
				}
				deleteGatewayChannel(channelCode, subChannel);
				deleteGatewayChannel(tradAgentInfoCY.getChannelCode(), tradAgentInfoCY.getSubChannelCode());
				agentInfoMtService.deleteAgentMtInfo(tradAgentInfoCY);
				agentInfoMtService.deleteAgentMtInfo(tradAgentInfo);
			} else if ("deleteCY".equals(flag)) {
				// 当前为意健险配置，直接删除,并更改所关联车险配置的key1
				String subChannelAsCar = "";
				if (subChannel.endsWith("_CY")){
					subChannelAsCar = subChannel.substring(0, subChannel.length()-3);
				} else {
					return Result.error("系统错误，请联系管理员处理！");
				}
				TradAgentInfo tradAgentInfoAsCar = new TradAgentInfo();
				// 使用合作伙伴代码和子机构代码查询当前意健险销售配置所关联的车险销售配置
				tradAgentInfoAsCar.setChannelCode(channelCode);
				tradAgentInfoAsCar.setSubChannelCode(subChannelAsCar);
				List<TradAgentInfo> tradAgentInfos = carPushDataQueryService.queryTradAgentInfo(tradAgentInfoAsCar);
				// 获取车险销售渠道配置
				tradAgentInfoAsCar = tradAgentInfos.get(0);
				// 将key1设置为空，当删除掉意健险配置后，解除车险配置的关联
				tradAgentInfoAsCar.setKey1("");
				deleteGatewayChannel(channelCode, subChannel);
				agentInfoMtService.updateAgentMtInfo(tradAgentInfoAsCar);
				agentInfoMtService.deleteAgentMtInfo(tradAgentInfo);
			} else if ( "delete".equals(flag)) {
				// 当前为单车险配置
				List<TradAgentInfoRela> tradAgentInfoRelaList = carPushDataQueryService.queryCarAgentRelaInfo(tradAgentInfoRela);
				if (tradAgentInfoRelaList.size() > 0) {
					// 如果有关联方案，删除掉
					agentInfoMtService.deleteTradAgentInfoRela(id.trim());
				}
				deleteGatewayChannel(channelCode, subChannel);
				agentInfoMtService.deleteAgentMtInfo(tradAgentInfo);
			}
		} else {
			return Result.error("系统错误，请联系管理员处理！");
		}
		return Result.success("删除成功");
	}
	/**
	 * 加载广东销售信息
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/loadSale")
	@ResponseBody
	public Map<String,Object> loadSale(String id) throws Exception{
		Map<String, Object> map = new HashMap<String,Object>();
		try {
			/**车险销售人员字典*/
			List<DictDto> saleMenTypes=DictCache.getDict(Constants.CAR_SALE_MEN_TYPE);
			List<DictDto> saleTypes=DictCache.getDict(Constants.CAR_SALES_TYPE);
			List<TradSaleAgent> saleAgents=agentInfoMtService.queryTrandSaleAgent(id);
			map.put("saleMenTypes", saleMenTypes);
			map.put("saleTypes", saleTypes);
			map.put("saleAgents", saleAgents);
			map.put("success", true);
		} catch (Exception e) {
			map.put("success", false);
			map.put("message", e.getMessage());
		}
		return map;
	}
	/***
	 * 销售信息保存
	 */
	@RequestMapping(value = "/addTradSaleAgent")
	@ResponseBody
	public Result addTradSaleAgent(String id,String saleArry) throws Exception {
		return addTradSale(id, saleArry);
	}
	private Result addTradSale(String id,String saleArry) throws Exception{
		Result result = null;
		if(StrUtil.isNotEmpty(id)){
			Map<String, String> map=new HashMap<String, String>();
			map.put("id", id);
			agentInfoMtService.deleteTrade(id);
			List<Map<String,String>> list = JsonUtils.parseJson(saleArry, ArrayList.class);
			List<TradSaleAgent> planSales=new ArrayList<TradSaleAgent>();
			for (Map<String, String> map2 : list) {
				TradSaleAgent planSale=new TradSaleAgent();
				planSale.setId(Long.parseLong(id));
				planSale.setSeqNo(map2.get("seqNo"));
				planSale.setSaleType(map2.get("saleType"));
				planSale.setPracticeNo(map2.get("practiceNo"));
				planSale.setPersonType(map2.get("personType"));
				planSale.setSalePerson(map2.get("salePerson"));
				planSale.setEmpNo(map2.get("empNo"));
				planSale.setPlanType(map2.get("planType"));
				planSale.setInsertDate(new Date());
				planSale.setAgentFee((Double.parseDouble(map2.get("agentFee"))+""));
				planSales.add(planSale);
			}
			Boolean flag=agentInfoMtService.addTrade(planSales);
			if(flag){
				result=Result.success("添加成功");
			}else{
				result=Result.error("添加失败");	
			}
		}else{
			result=Result.error("代理信息ID为空");
		}
		return result;
	
	}
	@RequestMapping(value ="/savaorupdateServiceInfo")
	@ResponseBody
	public Map<String,Object> savaorupdateServiceInfo(String serviceInfo,String subChannelCode)throws Exception{
		List<DictDto> servicesDictInfo = getDictInfo("INSAIC_NLIFE_SERVICE%",subChannelCode,"Y");
		String sql = "";
		Map<String, Object> paramMap = new HashMap<String,Object>();
		if(null!=servicesDictInfo && servicesDictInfo.size()>0){
			sql = "update t_gateway_dict d set d.code='"+serviceInfo+"' where d.code_type='INSAIC_NLIFE_SERVICE' and d.other_code='"+subChannelCode+"'";
		}else{
			sql = "insert into t_gateway_dict (CODE_TYPE, CODE,CODE_DESC, CODE_STATUS,OTHER_CODE) values ('INSAIC_NLIFE_SERVICE','"+serviceInfo+"','上汽服务代码服务名称配置','1','"+subChannelCode+"')";
		}
		try {
			if(saveOrupdateDict(sql)){
				paramMap.put("success", "操作成功");
			}else{
				paramMap.put("error", "系统错误请联系管理员");
			}
		} catch (Exception e) {
			paramMap.put("error", "系统错误请联系管理员");
		}
		return paramMap;
	}
	@RequestMapping(value ="/savaorupdateAgentsInfo")
	@ResponseBody
	public Map<String, Object> savaorupdateAgentsInfo(String subChannelCode,
			String dept, String agents, String circuitFlag , String agentName) throws Exception {
		String sql = "";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		if ("Y".equals(circuitFlag)) {
			List<DictDto> dictInfo = getDictInfo("insaic_cfiAgents" + subChannelCode + "%", subChannelCode, "Y");
			if (null != dictInfo && dictInfo.size() > 0) {
				sql = "update t_gateway_dict d set d.code='" + agents + "' ， d.other_name = '"+ agentName +"' where d.code_type='insaic_cfiAgents" + subChannelCode + "' and d.other_code='" + subChannelCode + "'";
			} else {
				sql = "insert into t_gateway_dict (CODE_TYPE, CODE,CODE_DESC, CODE_STATUS,OTHER_CODE , OTHER_NAME) values ('insaic_cfiAgents" + subChannelCode + "','" + agents + "','上汽代理人信息配置','1','" + subChannelCode + "','" + agentName + "')";
			}
		} else {
			List<DictDto> dictInfo = getDictInfo("insaic_cfiAgents%",dept.substring(0, 2) + "%", "N");
			Map<String, String> deptMap = new HashMap<String, String>();
			if (null != dictInfo && dictInfo.size() > 0) {
				for (DictDto dictDto : dictInfo) {
					deptMap.put(dictDto.getOtherCode(), dictDto.getCode());
				}
			}
			if (deptMap.size()>0 && StrUtil.isNotEmpty(deptMap.get(dept))) {
				sql = "update t_gateway_dict d set d.code='" + agents + "' , d.other_name = '"+ agentName +"' where d.code_type='insaic_cfiAgents" + dept + "' and d.other_code='" + dept + "'";
			} else {
				sql = "insert into t_gateway_dict (CODE_TYPE, CODE,CODE_DESC, CODE_STATUS,OTHER_CODE , OTHER_NAME) values ('insaic_cfiAgents" + dept + "','" + agents + "','上汽代理人信息配置','1','" + dept + "','" + agentName + "')";
			}
		}
		try {
			if (saveOrupdateDict(sql)) {
				paramMap.put("success", "操作成功");
			} else {
				paramMap.put("error", "系统错误请联系管理员");
			}
		} catch (Exception e) {
			paramMap.put("error", "系统错误请联系管理员");
		}
		return paramMap;
	}
	private static boolean saveOrupdateDict(String sql) throws AppException, SQLException{
		DataSource ds = (DataSource)ApplicationContextUtil.getBean("dataSource");
		if(ds == null){
			throw new AppException("无法获取数据源:"+ ds);
		}
		Connection conn = null;
		PreparedStatement pstmt = null;
		boolean execute = true;
		try{
			conn = ds.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.execute(sql);
			conn.commit();
		}finally{
			BaseDaoImpl.close(pstmt);
			BaseDaoImpl.close(conn);
		}
		return execute;
	}

	private static List<DictDto> getDictInfo(String codeType,String param,String flag) throws AppException, SQLException{
		//flag = Y || N || M(more)
		DataSource ds = (DataSource)ApplicationContextUtil.getBean("dataSource");
		if(ds == null){
			throw new AppException("无法获取数据源:"+ ds);
		}
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		List<DictDto> list = null;
		String sql = "";
		if("Y".equals(flag)){
			sql = "select  code_type,code,other_code from t_gateway_dict where code_type like '"+codeType+"' and other_code = '"+param+"' and code_status='1'  ";
		}else if("YM".equals(flag)){
			sql = "select  code_type,code,other_code,other_name from t_gateway_dict where code_type like '"+codeType+"' and other_code = '"+param+"' and code_status='1'  ";
		}else if("NM".equals(flag)){
			sql = "select  code_type,code,other_code,other_name from t_gateway_dict where code_type like '"+codeType+"' and other_code like '"+param+"' and code_status='1'  ";
		}
		else{
			sql = "select  code_type,code,other_code from t_gateway_dict where code_type like '"+codeType+"' and other_code like '"+param+"' and code_status='1'";
		}
		try{
			conn = ds.getConnection();
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while (rs.next()){
				if(list == null){
					list = new ArrayList<DictDto>();
				}
				DictDto dd = new DictDto();
				dd.setCodeType(rs.getString("code_type"));
				dd.setCode(rs.getString("code"));
				dd.setOtherCode(rs.getString("other_code"));
				if("YM".equals(flag) || "NM".equals(flag)){
					dd.setOtherName(rs.getString("other_name"));
				}
				list.add(dd);
			}
		}finally{
			BaseDaoImpl.close(rs);
			BaseDaoImpl.close(pstmt);
			BaseDaoImpl.close(conn);
		}
		return list;
	}
	
	/**
	 * 删除相关的GatewaySubChannel子机构
	 * @param channelCode 机构代码
	 * @param subChannel 子机构代码
	 * @throws Exception 。
	 */
	private void deleteGatewayChannel(String channelCode, String subChannel) throws Exception {
		GatewaySubChannel gatewaySubChannel = new GatewaySubChannel();
		gatewaySubChannel.setSubChannelCode(subChannel);
		gatewaySubChannel.setFkChannelCode(channelCode);
		List<GatewaySubChannel> gatewaySubChannels = gatewaySubChannelService.querySubChannelListBySubChannel(gatewaySubChannel);
		if (null != gatewaySubChannels) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("subChannelCode", subChannel);
			map.put("fkChannelCode", channelCode);
			gatewaySubChannelService.delSubChannel1(map);
		}
	}
	private String getAgentTypeByNewBsnsType(String newBsnsType,List<DictDto> newBusinessSource) {
		String agentType = "";
		for (DictDto dictDto : newBusinessSource) {
			if (newBsnsType.equals(dictDto.getCode())){
				if ("1900101".equals(dictDto.getOtherCode2())){
					agentType = "0";
					break;
				}else if ("1900203".equals(dictDto.getOtherCode2())) {
					agentType = "1";
					break;
				}else if ("1900201".equals(dictDto.getOtherCode2())) {
					agentType = "2";
					break;
				}else if ("1900202".equals(dictDto.getOtherCode2())) {
					agentType = "3";
					break;
				}else if ("1900301".equals(dictDto.getOtherCode2())) {
					agentType = "4";
					break;
				}
			}
		}
		return agentType;
	}
}
